package myJs.user.blast

import myJs.Implicits._
import myJs.Utils
import myJs.Utils._
import myJs.myPkg._
import myJs.myPkg.jquery._
import myJs.tool.Tool
import org.scalajs.dom._
import org.scalajs.dom.ext.Ajax
import scalatags.Text.all._

import scala.concurrent.ExecutionContext.Implicits.global
import scala.scalajs.js
import scala.scalajs.js.Dynamic.{global => g}
import scala.scalajs.js.JSConverters._
import scala.scalajs.js.JSON
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}

/**
 * Created by yz on 16/9/2021
 */
@JSExportTopLevel("BlastResult")
object BlastResult {

  @JSExport("init")
  def init = {
    refreshHtml
  }

  def refreshHtml = {
    val url = g.jsRoutes.controllers.BlastController.blastResult().url.toString
    val dict = js.Dictionary(
      "path" -> getPath
    )
    Ajax.post(url = s"${url}", data = JSON.stringify(dict), headers = Map("Content-Type" -> "application/json")).map { xhr =>
      val rs = xhr.responseText.toJDJAn
      $("#resultContent").html(rs.myGet("html"))
      $(".detail-info").hide()
      val blocks = rs("block").toJArJDJAn
      blocks.foreach { dict =>
        val id = s"#synteny${dict.myGet("index")}"
        val data = dict("data")
        val relate = dict("relate")
        val index = s"${dict.myGet("index")}-"
        g.DisplayBlock(id, data, relate, index)
      }
      $(".others").hide()
      val url = g.jsRoutes.controllers.BlastController.blastResultBefore().url.toString
      val finalUrl = s"http://${window.location.host}${url}"
      window.parent.postMessage("success", finalUrl)
    }
  }

  @JSExport("downloadByName")
  def downloadByName(name: String) = {
    val url = g.jsRoutes.controllers.BlastController.downloadByName().url.toString
    val id = getId
    window.location.href = s"${url}?name=${name}&id=${id}"
  }

  @JSExport("downloadByRange")
  def downloadByRange(name: String, obj: String) = {
    val url = g.jsRoutes.controllers.BlastController.downloadByRange().url.toString
    val id = getId
    val range = $(s".${obj}").text()
    window.location.href = s"${url}?name=${name}&id=${id}&range=${range}"
  }


  def getPath = {
    g.path.toString
  }

  def getId = {
    g.id.toString
  }


}
